﻿using PLCS.App.Shared.Extensions;
using PLCS.App.Shared.ViewModels;
using PLCS.Application.Contracts.ErrorLogApp.Dtos;
using PLCS.Client.IService.LogManager;
using PLCS.Client.Service.Client;

using System.Collections.Generic;

namespace PLCS.App.ViewModels.Dialogs;

public class ErrorDialogViewModel : HostDialogViewModel
{
    private readonly IErrorLogService _errorLogService;

    private ObservableCollection<ErrorLogDto> _errorList;
    public DelegateCommand DisposeErrorCommand { get; set; }
    public DelegateCommand DisposeAllErrorCommand { get; set; }
    public DelegateCommand<ErrorLogDto> SelectErrorCommand { get; set; }

    private ErrorLogDto _selectError;

    public ErrorLogDto SelectError
    {
        get { return _selectError; }
        set { SetProperty(ref _selectError, value); }
    }

    private bool _isDialogOpen;

    public bool IsDialogOpen
    {
        get { return _isDialogOpen; }
        set { SetProperty(ref _isDialogOpen, value); }
    }

    public ObservableCollection<ErrorLogDto> ErrorList
    {
        get { return _errorList; }
        set { SetProperty(ref _errorList, value); }
    }

    public override async void OnDialogOpened(IDialogParameters parameters)
    {
        var res = await _errorLogService.GetUnDisposedErrorAsync();
        ErrorList = res.ToObservable();
    }

    public ErrorDialogViewModel(IErrorLogService errorLogService)
    {
        View = "异常日志弹窗";
        _errorLogService = errorLogService;
        DisposeErrorCommand = new DelegateCommand(DisposeError);
        SelectErrorCommand = new DelegateCommand<ErrorLogDto>(SelectErrorMethod);
        ErrorList = new ObservableCollection<ErrorLogDto>();
        //DisposeAllErrorCommand = new DelegateCommand(DisposeAllError);
    }

    private void SelectErrorMethod(ErrorLogDto dto)
    {
        SelectError = dto;
    }

    //private async void DisposeAllError()
    //{
    //    try
    //    {
    //        await _errorLogService.DiseposeAllErrorAsync();
    //        ErrorList.RemoveAll(x => x.Message != null);
    //    }
    //    catch (Exception ex)
    //    {
    //        ShowMessage("报警清除失败");
    //    }
    //}

    private async void DisposeError()
    {
        if (string.IsNullOrEmpty(SelectError.Reason) || string.IsNullOrEmpty(SelectError.Solution))
        {
            ShowMessage("请输入原因和解决方案");
            return;
        }
        try
        {
            await _errorLogService.DiseposeErrorAsync(SelectError.Id, SelectError.Reason, SelectError.Solution);
            ErrorList.Remove(SelectError);
            IsDialogOpen = false;
            if (!ErrorList.Any())
                Save();
            Log("处理异常", SelectError);
        }
        catch (Exception ex)
        {
            ShowMessage("报警清除失败");
        }
    }
}